<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP5.1_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: ZhangXuanNeng <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\api\model\SavephoneLog;
use think\Db;

/**
 * 会员-模型
 * @author ZhangXuanNeng
 * @since 2020/11/20
 * Class Member
 * @package app\admin\model
 */
class Member extends BaseModel
{
    // 设置数据表名
    protected $name = 'member';

    /**
     * 获取会员信息
     * @param int $id 会员ID
     * @return 数据信息|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since 2020/11/20
     * @author ZhangXuanNeng
     */
    public function getInfo($id)
    {
        $info = parent::getInfo($id); // TODO: Change the autogenerated stub
        if ($info) {
            // 头像
//            if ($info['avatar']) {
//                $info['avatar'] = get_image_url($info['avatar']);
//            }
//            // 出生日期
//            if ($info['birthday']) {
//                $info['birthday'] = datetime($info['birthday']);
//            }
//            // 城市
//            $city = [];
//            $city[] = !empty($info['province_code']) ? strval($info['province_code']) : "";
//            $city[] = !empty($info['city_code']) ? strval($info['city_code']) : "";
//            $city[] = !empty($info['district_code']) ? strval($info['district_code']) : "";
//            $info['city'] = $city;
        }
        return $info;
    }
    /**
     * 推广员换绑信息获取
     * @return array
     */
    public function getMemberGamePromoteInfo($member_id)
    {
        $gameRoleLists = Db::name('game_role')
            ->where('parent_member_id',$member_id)
            ->field('id,package_id,package_name,game_id,server_id,server_name,role_id,role_name,role_level,promote_id,promote_account,add_time,play_time')
            ->select();
        $gameIds = [];
        foreach ($gameRoleLists as $k=>$v){
            $gameIds[$k] = $v['game_id'];
        }
        $gameLists = Db::name('game')
            ->where('id','in',$gameIds)
            ->field('id,game_name')
            ->select();
        $msg = array(
            'code'  => 0,
            'msg'   => '请求成功',
            'data'  => ['gameRoleLists'=>$gameRoleLists,'gameLists'=>$gameLists]
        );
        return $msg;
    }
    /**
     * 获取玩家游戏推广员
     * @return array
     */
    public function getMemberGamePromote($member_id,$game_id){
        $promote_id = Db::name('member_package_promote')->where(['member_id'=>$member_id,'game_id'=>$game_id])->value('promote_id');
        $msg = array(
            'code'  => 0,
            'msg'   => '请求成功',
            'data'  => Db::name('user_promote')->where('id',$promote_id)->value('realname')
        );
        return $msg;
    }
    /**
     * 更新玩家游戏推广员
     * @return array
     */
    public function setMemberGamePromote($data){
        Db::startTrans();
        try {
            $info = Db::name('member_package_promote')
                ->where(['member_id'=>$data['member_id'],'game_id'=>$data['game_id']])
                ->find();
            Db::name('member_package_promote')
                ->where(['member_id'=>$data['member_id'],'game_id'=>$data['game_id']])
                ->update(['promote_id'=>$data['new_promote_id']]);
            $userModel = 'user';
            if(isset($data['is_promote']) && !empty($data['is_promote'])){
                $userModel = 'user_promote';
            }
            $logData = array(
                'member_id'     => $data['member_id'],
                'game_id'       => $data['game_id'],
                'old_promote_id'=> $info['promote_id'],
                'new_promote_id'=> $data['new_promote_id'],
                'op_admin_id'   => $this->userId,
                'op_admin_name' => Db::name($userModel)->where('id',$this->userId)->value('realname'),
                'remark'        => $data['remark'],
                'create_time'   => date("Y-m-d H:i:s")
            );
            $save = array(
                'promote_id'    => $data['new_promote_id'],
                'promote_account'=> Db::name('user_promote')->where('id',$data['new_promote_id'])->value('realname')
            );
            Db::name('member')->where('id',$data['member_id'])
                ->whereOr(function($query) use ($data){
                    $query->where('pid',$data['member_id'])->where('game_id',$data['game_id']);
                })->update($save);
            Db::name('game_role')->where('game_id',$data['game_id'])->where('parent_member_id',$data['member_id'])->update($save);
            Db::name('member_package_promote_log')->insert($logData);
            Db::commit();
            $msg = array(
                'code'  => 0,
                'msg'   => '请求成功',
                'data'  => []
            );
            return $msg;
        }catch (\Exception $e){
            Db::rollback();
            $msg = array(
                'code'  => -1,
                'msg'   => $e->getMessage(),
                'data'  => ''
            );
            return $msg;
        }

    }
    /**
     * 批量更新玩家游戏推广员
     * @return array
     */
    public function setMemberGamePromoteBatch($data){
        Db::startTrans();
        try {
            Db::name('member_package_promote')
                ->where(['game_id'=>$data['game_id'],'promote_id'=>$data['old_promote_id']])
                ->update(['promote_id'=>$data['new_promote_id']]);
            $logData = array(
                'game_id'       => $data['game_id'],
                'old_promote_id'=> $data['old_promote_id'],
                'new_promote_id'=> $data['new_promote_id'],
                'op_admin_id'   => $this->userId,
                'op_admin_name' => Db::name('user')->where('id',$this->userId)->value('realname'),
                'remark'        => $data['remark'],
                'create_time'   => date("Y-m-d H:i:s")
            );
            $save = array(
                'promote_id'    => $data['new_promote_id'],
                'promote_account'=> Db::name('user_promote')->where('id',$data['new_promote_id'])->value('realname')
            );
            Db::name('member')
                ->where('game_id',$data['game_id'])
                ->where('promote_id',$data['old_promote_id'])
                ->update($save);
            Db::name('game_role')->where('game_id',$data['game_id'])
                ->where('promote_id',$data['old_promote_id'])
                ->update($save);
            Db::name('member_package_promote_batch_log')->insert($logData);
            Db::commit();
            $msg = array(
                'code'  => 0,
                'msg'   => '请求成功',
                'data'  => []
            );
            return $msg;
        }catch (\Exception $e){
            Db::rollback();
            $msg = array(
                'code'  => -1,
                'msg'   => $e->getMessage(),
                'data'  => ''
            );
            return $msg;
        }

    }

    /**
     * 换绑小号
     * @return array
     */
    public function setMemberChild($data){
        try {
            $userInfo = $this->where('id',$data['id'])->find();
            if($userInfo['pid'] == 0){
                return message('被转移数据非小号',false);
            }
            $parentInfo = $this->where('id',$data['pid'])->find();
            if(!$parentInfo || $parentInfo['pid'] != 0){
                return message('转移数据不存在或非主号',false);
            }
            $logData = array(
                'child_id'      => $data['id'],
                'old_pid'       => $userInfo['pid'],
                'new_pid'       => $data['pid'],
                'create_user'   => $this->userId,
                'create_time'   => date("Y-m-d H:i:s"),
                'remark'        => $data['remark']
            );
            $save = array(
                'pid'    => $data['pid'],
            );
            Db::name('member')
                ->where('id',$data['id'])
                ->update($save);
            Db::name('member_child_log')->insert($logData);
            $msg = array(
                'code'  => 0,
                'msg'   => '请求成功',
                'data'  => []
            );
            return $msg;
        }catch (\Exception $e){
            $msg = array(
                'code'  => -1,
                'msg'   => $e->getMessage(),
                'data'  => ''
            );
            return $msg;
        }

    }
    /**
     * 获取账号信息
     * @return array
     */
    public function getAccount($data)
    {
        try {
            $userName = $this->where('id', $data['id'])->value('username');
            if (preg_match('/^1([0-9]{10})$/', $userName)) {
                $userName = substr_replace($userName, '****', 3, -4);
            }
            $msg = array(
                'code' => 0,
                'msg' => '请求成功',
                'data' => ['username' => $userName]
            );
            return $msg;
        } catch (\Exception $e) {
            $msg = array(
                'code' => -1,
                'msg' => $e->getMessage(),
                'data' => ''
            );
            return $msg;
        }
    }
    /**
     * 换绑手机
     * @return array
     */
    public function setMemberPhone($data){
        try {
            $userInfo = $this->where('id',$data['id'])->find();
            $logData = array(
                'member_id'     => $data['id'],
                'source'        => '总后台',
                'prev_phone'    => $userInfo['phone'],
                'phone'         => $data['phone'],
                'operator'      => Db::name('user')->where('id',$this->userId)->value('realname'),
                'add_time'      => time(),
                'remark'        => $data['remark']
            );
            $save = array(
                'phone'    => $data['phone'],
            );
            if($userInfo['phone'] == $userInfo['username']){
                $save['username'] = $data['phone'];
            }
            $map[] = ['id','<>',$data['id']];
            $map[] = ['phone','=',$data['phone']];
            $status = $this->where($map)->find();
            if($status){
                return message('手机号已被占用',false);
            }
            $this->where('id',$data['id'])->update($save);
            $savePhone = new SavephoneLog();
            $savePhone->insert($logData);
            $msg = array(
                'code'  => 0,
                'msg'   => '请求成功',
                'data'  => []
            );
            return $msg;
        }catch (\Exception $e){
            $msg = array(
                'code'  => -1,
                'msg'   => $e->getMessage(),
                'data'  => ''
            );
            return $msg;
        }

    }
}